from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime, date
from ..core.database import get_db
from ..core.dependencies import get_current_active_user, get_current_admin_user
from ..models.user import User
from ..services.attendance_service import AttendanceService
from ..schemas.attendance import AttendanceRecord as AttendanceSchema, ClockResponse, AttendanceSummary

router = APIRouter(prefix="/attendance", tags=["attendance"])

@router.post("/clock-in", response_model=ClockResponse)
def clock_in(current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    """普通用户打卡上班"""
    attendance_service = AttendanceService(db)
    record = attendance_service.clock_in(current_user.id)
    
    # 检查是否已经打卡过
    if record.clock_in_time != datetime.now():
        message = "您今天已经打卡过了"
    else:
        message = "打卡成功"
    
    return {
        "message": message,
        "user": current_user.username,
        "action": "clock_in",
        "timestamp": record.clock_in_time,
        "status": record.status
    }

@router.post("/clock-out", response_model=ClockResponse)
def clock_out(current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    """普通用户打卡下班"""
    attendance_service = AttendanceService(db)
    record = attendance_service.clock_out(current_user.id)
    
    if not record:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="您今天还没有上班打卡，无法下班打卡"
        )
    
    return {
        "message": "打卡成功",
        "user": current_user.username,
        "action": "clock_out",
        "timestamp": record.clock_out_time,
        "status": record.status
    }

@router.get("/my-records", response_model=List[AttendanceSchema])
def get_my_attendance_records(
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """普通用户查看自己的考勤记录"""
    attendance_service = AttendanceService(db)
    return attendance_service.get_user_attendance_records(current_user.id, start_date, end_date)

@router.get("/department-summary", response_model=AttendanceSummary)
def get_department_attendance_summary(
    department_id: int,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    current_user: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """管理员查看部门考勤汇总"""
    attendance_service = AttendanceService(db)
    return attendance_service.get_department_attendance_summary(department_id, start_date, end_date)

@router.get("/profile")
def get_user_profile(current_user: User = Depends(get_current_active_user)):
    """普通用户查看个人资料"""
    return {
        "id": current_user.id,
        "username": current_user.username,
        "email": current_user.email,
        "full_name": current_user.full_name,
        "department_id": current_user.department_id,
        "is_active": current_user.is_active
    }